<template>
  <div class="login">
    <van-form @submit="onSubmit">
      <van-field
          v-model="username"
          name="username"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
          v-model="password"
          type="password"
          name="password"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">
          登录
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import Vue from 'vue';
import { Form,Field } from 'vant';
import {setToken} from "@/utils/auth";
Vue.use(Form);
Vue.use(Field);
export default {
  name: "login",
  data() {
    return {
      username: '',
      password: '',
    };
  },
  methods: {
    async onSubmit(values) {
      const envId = this.$cloudbase.config.env;
      const res = await fetch(`https://${envId}.service.tcloudbase.com/login`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },

        body: JSON.stringify(values)
      });

      if (res.status !== 200) return;
      const data = await res.json();
      if (data.status === 200) {
        try {
          await this.$cloudbase
              .auth({persistence: "local"})
              .signInWithTicket(data.message);
          setToken(data.message);
          this.$router.push("/");
        } catch (e) {
          console.error(e);
          console.log(e.code);
        }
      }
    },
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
}
</script>

<style scoped>
.login{
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>